package com.wjr.braveheart.utils;

import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * @Description: 对 Assets 目录下文件操作的工具类
 * @Author: 长安三日
 * @Email: 忘了
 * @CreateDate: 2020/5/8 13:14
 * @UpdateRemark: 更新说明：注意申请读写权限
 * @Version: 1.0
 * PS: You can change the world with code! Don't give up!
 */
public class AssetsFileUtils {

    /**
     * 获取assets目录下文件中String字符串
     *
     * @param context 上下文
     * @param srcPath assets下目标文件的路径
     * @return String
     */
    public static String getString(Context context, String srcPath) {
        StringBuilder stringBuilder = new StringBuilder();
        try {
            AssetManager assetManager = context.getAssets();
            BufferedReader bf = new BufferedReader(new InputStreamReader(
                    assetManager.open(srcPath)));
            String line;
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }

    /**
     * 获取assets目录下的图片
     *
     * @param context 上下文
     * @param srcPath assets下目标文件的路径
     * @return Bitmap
     */
    public static Bitmap getBitmap(Context context, String srcPath) {
        Bitmap bitmap = null;
        AssetManager assetManager = context.getAssets();
        try {
            InputStream is = assetManager.open(srcPath);
            bitmap = BitmapFactory.decodeStream(is);
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return bitmap;
    }


    /**
     * 获取assets目录下的单个文件
     * 只能用于webView加载
     *
     * @param srcPath assets下目标文件的路径
     * @return File
     */
    public static File getFile(String srcPath) {
        //这种方式只能用于webView加载，直接取路径是不行的
        String path = "file:///android_asset/" + srcPath;
        File file = new File(path);
        return file;

    }

    /**
     * 获取assets目录下所有文件
     *
     * @param srcPath assets下目标文件的路径
     * @return String[]
     */
    public static String[] getFiles(Context context, String srcPath) {
        AssetManager assetManager = context.getAssets();
        String[] files = null;
        try {
            files = assetManager.list(srcPath);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return files;

    }

    /**
     * 将assets目录下的目标文件拷贝到sd卡指定目录下
     * （默认不覆盖已存在目标文件）
     *
     * @param context 上下文
     * @param srcPath assets下目标文件的路径
     * @param dstPath sd卡的路径
     */
    public static void copyAssetsFileToSDCard(Context context, String srcPath, String dstPath) {
        copyAssetsFileToSDCard(context, srcPath, dstPath, false);
    }

    /**
     * 将assets目录下的目标文件拷贝到sd卡指定目录下
     *
     * @param context 上下文
     * @param srcPath assets下目标文件的路径
     * @param dstPath sd卡的路径
     * @param isCover 是否覆盖文件
     */
    public static void copyAssetsFileToSDCard(Context context, String srcPath, String dstPath, boolean isCover) {
        //获取目标文件名
        String fileName = new File(srcPath).getName();
        //判断sd卡目录是否存在，若不存在则创建改目录
        File folder = new File(dstPath);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        //判断是否已经拷贝目标文件，是否覆盖
        File file = new File(dstPath + File.separator + fileName);
        if (isCover || (!isCover && !file.exists())) {
            try {
                InputStream is = context.getAssets().open(srcPath);
                FileOutputStream fos = new FileOutputStream(new File(dstPath + File.separator + fileName));
                byte[] buffer = new byte[1024];
                int byteCount;
                // 循环从输入流读取buffer字节
                while ((byteCount = is.read(buffer)) != -1) {
                    // 将读取的输入流写入到输出流
                    fos.write(buffer, 0, byteCount);
                }
                // 刷新缓冲区
                fos.flush();
                is.close();
                fos.close();
            } catch (IOException e) {
                Log.e("AssetsFileUtils", "copyAssetsFileToSDCard: " + e.toString());
            }
        }
    }

    /**
     * 将assets目录下的目标文件夹的文件拷贝到sd卡指定目录下
     *
     * @param context 上下文
     * @param srcPath assets下目标文件夹的路径
     * @param dstPath sd卡的路径
     */
    public static void copyAssetsFilesToSDCard(Context context, String srcPath, String dstPath) {
        try {
            String fileNames[] = context.getAssets().list(srcPath);
            if (fileNames.length > 0) {
                File file = new File(dstPath);
                if (!file.exists()) file.mkdirs();
                for (String fileName : fileNames) {
                    if (!srcPath.equals("")) {
                        // assets 文件夹下的目录
                        copyAssetsFilesToSDCard(context, srcPath + File.separator + fileName, dstPath + File.separator + fileName);
                    } else {
                        // assets 文件夹
                        copyAssetsFilesToSDCard(context, fileName, dstPath + File.separator + fileName);
                    }
                }
            } else {
                File outFile = new File(dstPath);
                InputStream is = context.getAssets().open(srcPath);
                FileOutputStream fos = new FileOutputStream(outFile);
                byte[] buffer = new byte[1024];
                int byteCount;
                while ((byteCount = is.read(buffer)) != -1) {
                    fos.write(buffer, 0, byteCount);
                }
                fos.flush();
                is.close();
                fos.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("AssetsFileUtils", "copyAssetsFilesToSDCard: " + e.toString());
        }
    }

}
